package cn.com.woxitech.dev.controller.websocket;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.web.socket.messaging.SessionConnectEvent;

import cn.com.woxitech.dev.common.RoomWebSocketSession;
import cn.com.woxitech.dev.model.gen.WmRoom;
import cn.com.woxitech.dev.model.gen.WmUser;
import cn.com.woxitech.dev.service.RoomService;
import cn.com.woxitech.dev.service.UserService;

@Configuration
public class StompConnectedEvent implements ApplicationListener<SessionConnectEvent> {

	@Autowired
	private UserService userService;

	@Autowired
	private RoomService roomService;
	
    @Autowired
    public SimpMessagingTemplate simp;
    
    
	@Override
	public void onApplicationEvent(SessionConnectEvent event) {
		// TODO Auto-generated method stub
		
		StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
		if(sha.getNativeHeader("userid") == null){
			return;
		}
		String userid = sha.getNativeHeader("userid").get(0);
		String roomid = sha.getNativeHeader("roomid").get(0);
		String sessionid = sha.getSessionId();
		WmUser user = userService.getUserByUuid(userid);
		WmRoom room = roomService.getRoomsByUuid(roomid);
		
		Map<String, Object> attributes = new HashMap<String, Object>();
		//初次连接成功后获取用户的信息，并保存在服务器内存中。
		attributes.put("useruuid", userid);
		attributes.put("userInfo", user);
		attributes.put("roomuuid", roomid);
		attributes.put("roomInfo", room);
		
		//保存在线用户
		roomService.saveUserOnline(userid,roomid);
		
		//不保存login记录
		//savehistory
		
		RoomWebSocketSession.getInstance().setAttributes(sessionid, attributes);
		Map<String, Object> mp = new HashMap<String,Object>();
		mp.put("sessionid", sha.getSessionId());

		
	}

}